﻿using System;
using System.Linq;
using System.Collections.Generic;
using Cos.Core.Model.Common;
using Cos.Core.NHibernate;
using Cos.Module.Configuration.Data;
using NHibernate;
using NHibernate.Criterion;

namespace Cos.Module.Configuration.NHibernate
{
    public class CultureRepository : RepositoryBase, ICultureRepository
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="CultureRepository"/> class.
        /// </summary>
        /// <param name="sessionFactory">The session factory.</param>
        public CultureRepository(ISessionFactory sessionFactory)
            : base(sessionFactory)
        {
        }

        /// <summary>
        /// Get the default culture
        /// </summary>
        /// <returns>
        /// The default culture
        /// </returns>
        public Culture GetDefaultCulture()
        {
            var culture = this.CurrentSession.CreateCriteria<CultureDataModel>().Add(Restrictions.Eq("IsDefault", true)).UniqueResult<CultureDataModel>();

            return culture == null ? null : culture.ToModel();
        }

        /// <summary>
        /// Get all the cultures in the database
        /// </summary>
        /// <returns>
        /// All the cultures in the database
        /// </returns>
        public IEnumerable<Culture> GetCultures()
        {
            var cultures = this.CurrentSession.CreateCriteria<CultureDataModel>().List<CultureDataModel>();

            // If the dao returns null, don't crash
            if (cultures == null) 
            {
                return null;
            }

            return cultures.Select(x => x.ToModel());
        }

        public Culture GetCulture(string cultureCode)
        {
            var culture = this.CurrentSession.CreateCriteria<CultureDataModel>().Add(Restrictions.Eq("Id", cultureCode)).UniqueResult<CultureDataModel>();

            // TODO Exception when no culture returned

            return culture.ToModel();
        }

        public Culture SaveCulture(Culture culture)
        {
            var cultureDataModel = new CultureDataModel();

            cultureDataModel.Fill(culture);

            this.CurrentSession.SaveOrUpdate(cultureDataModel);

            this.CurrentSession.Flush();

            return cultureDataModel.ToModel();
        }
    }
}